<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="收费站" prop="deptId">
        <el-tree-select v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
          class="margin-right" placeholder="请选择部门" check-strictly clearable @change="bindChangeTree($event,'deptId')" />
      </el-form-item>
      
      <el-form-item label="开展时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeLaunchTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
   
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['coordination:race:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['coordination:race:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Menu" @click="handleStatistics">统计</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="raceList" @selection-change="handleSelectionChange" show-overflow-tooltip>
      <el-table-column label="序号" align="center" type="index" width="65" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="开展时间" align="center" prop="launchTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.launchTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="竞赛方案" align="center" prop="racePlan" >
        <template #default="scope">
          <el-button   @click.stop="previewFun(scope.row.racePlan)" v-if="scope.row.racePlan">查看</el-button> </template>
      </el-table-column>
      
      <el-table-column label="签到表" align="center" prop="signList">
        <template #default="scope">
          <el-button   @click.stop="previewFun(scope.row.signList)" v-if="scope.row.signList">查看</el-button> </template>
      </el-table-column>
      
      <el-table-column label="成绩表" align="center" prop="gradeList" >
        <template #default="scope">
          <el-button  @click.stop="previewFun(scope.row.gradeList)" v-if="scope.row.gradeList">查看</el-button> </template>
      </el-table-column>
      
      <!-- <el-table-column label="总结" align="center" prop="summary" /> -->
      <el-table-column label="现场照片" align="center" prop="imgUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imgUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleUpdate(scope.row,1)" >详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['coordination:race:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['coordination:race:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改技能竞赛对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="raceRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
        <el-form-item label="部门" prop="deptId">
          <el-tree-select  style="width:100%" v-model="form.deptId" :disabled="true" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
          class="margin-right" placeholder="请选择部门" check-strictly clearable  />
        </el-form-item>
      </el-col> <el-col :span="12" :xs="24">
        <el-form-item label="开展时间" prop="launchTime">
          <el-date-picker clearable  :disabled="isShow"
          style="width: 100%;"
            v-model="form.launchTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开展时间">
          </el-date-picker>
        </el-form-item>
      </el-col> <el-col :span="12" :xs="24">
        <el-form-item label="竞赛方案" prop="racePlan">
          <file-upload :disabled="isShow" v-model="form.racePlan"/>
        </el-form-item>
      </el-col> <el-col :span="12" :xs="24">
        <el-form-item label="签到表" prop="signList">
          <file-upload :disabled="isShow" v-model="form.signList"/>
        </el-form-item>
      </el-col> <el-col :span="12" :xs="24">
        <el-form-item label="成绩表" prop="gradeList">
          <file-upload :disabled="isShow" v-model="form.gradeList" />
        </el-form-item>
      </el-col> <el-col :span="12" :xs="24">
        
        <el-form-item label="现场照片" prop="imgUrl">
          <image-upload  v-model="form.imgUrl" :disabled="isShow"/>
        </el-form-item>
        
      </el-col> <el-col :span="24" :xs="24">
        <el-form-item label="总结" prop="summary">
          <el-input v-model="form.summary" type="textarea" placeholder="请输入内容" rows="6" :disabled="isShow" />
        </el-form-item>
      </el-col> <el-col :span="24" :xs="24">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"  rows="6" :disabled="isShow" />
        </el-form-item>
      </el-col>
      </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!isShow">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <Viewer ref="fileViewerRef" :dialog-doc="dialogDoc" />
    <Statistics :echartsData="statisticsData" ref="statisticsRef" @changeType="handleStatistics" />
  </div>
</template>

<script setup name="Race">
import moment from "moment";
import { listRace, getRace, delRace, addRace, updateRace,postRaceCount } from "@/api/coordination/race";
import { getCKInfo } from '@/utils/auth'
import { deptTreeSelect } from "@/api/system/user";
import Viewer from "@/components/Custom/viewer.vue";
import Statistics from "./components/Statistics.vue";
const baseUrl = import.meta.env.VITE_APP_BASE_API;

const { proxy } = getCurrentInstance();
const { coo_report_menu_type } = proxy.useDict('coo_report_menu_type');
const dialogDoc = ref(false)
const fileViewerRef = ref()
const raceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeLaunchTime = ref([]);
const deptId = ref(Number(getCKInfo('deptId')))
const deptOptions=ref([])
const isShow=ref(false)
const statisticsData = ref({ series: [{ data: [] }, { data: [] }], xaxis: [] })
const statisticsRef = ref()
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: deptId.value,
    userId: null,
    launchTime: null,
    racePlan: null,
    signList: null,
    gradeList: null,
    summary: null,
    imgUrl: null,
    menuType: 1
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询技能竞赛列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeLaunchTime && '' != daterangeLaunchTime) {
    queryParams.value.params["beginLaunchTime"] = daterangeLaunchTime.value[0];
    queryParams.value.params["endLaunchTime"] = daterangeLaunchTime.value[1];
  }
  listRace(queryParams.value).then(response => {
    raceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: deptId.value,
    userId: null,
    launchTime: null,
    racePlan: null,
    signList: null,
    gradeList: null,
    summary: null,
    imgUrl: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    menuType: 1
  };
  proxy.resetForm("raceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeLaunchTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isShow.value=false;
  open.value = true;
  title.value = "添加技能竞赛";
}

/** 修改按钮操作 */
function handleUpdate(row,type) {
  reset();
  const _id = row.id || ids.value
  getRace(_id).then(response => {
    form.value = response.data;
    open.value = true;
   
    if(type==1){
      isShow.value=true;
      title.value = "查看技能竞赛";
    }else{
      isShow.value=false;
      title.value = "修改技能竞赛";
    }
  });
  
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["raceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRace(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRace(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除技能竞赛编号为"' + _ids + '"的数据项？').then(function() {
    return delRace(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
function handleStatistics(date) {
  // 本年  本季度  本月
  if (!date || !date.startDate) {
    date.startDate = moment().format('YYYY-MM') + '-01'
    date.endDate = moment().endOf('month').format('YYYY-MM-DD')
  }
  statisticsData.value.xaxis = []
  statisticsData.value.series[0].data = []
  postRaceCount({
    "startTime": date.startDate,
    "endTime": date.endDate,
    "type": 1,
  }).then(res => {
    if (res.code == 200 && res.data) {
      res.data.forEach(item => {
        statisticsData.value.xaxis.push(item.deptName)
        statisticsData.value.series[0].data.push(item.openCount)
      })
      statisticsRef.value.open();
    }
  })
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('coordination/race/export', {
    ...queryParams.value
  }, `技能竞赛_${new Date().getTime()}.xlsx`)
}
// 预览
const previewFun = (file) => {
  dialogDoc.value = true;
  let data = {};
  // 上传过的文件组成完成的网络路径
  if (file&&file.indexOf(',')==-1) {
    data.src = `${baseUrl}${file}`;
  }else if(file&&file.indexOf(',')!=-1){
    let src=file.split(',');
    let srcArr=[]
    src.forEach(item=>{srcArr.push(`${baseUrl}${item}`)})
    data.src = srcArr.join(',');
    file=srcArr[0]
  }

  const arr = file.split(".");
  const suffix = arr[arr.length - 1];
  if (suffix == "docx" || suffix == "doc") {
    fileViewerRef.value?.viewDocx(data, '公文');
  } else if (suffix == "xlsx" || suffix == "xls") {
    fileViewerRef.value?.viewXlsx(data);
  } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
    fileViewerRef.value?.viewImg(data);
  } else if (suffix == "pdf") {
    fileViewerRef.value?.viewPdf(data);
  }
};


getList();
getDeptTree()
</script>
